<template>
	<view class="u-page">
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<u--form :model="userForm" ref="form1">
			<u-form-item label="Id" borderBottom required><u--input type="text" v-model="userForm.id" border="none" readonly></u--input></u-form-item>

			<u-form-item label="用户" prop="name" borderBottom required>
				<u--input type="text" v-model="userForm.name" border="none" placeholder="请输入用户" clearable></u--input>
			</u-form-item>

			<u-form-item label="邮箱" prop="email" borderBottom required>
				<u--input type="text" v-model="userForm.email" border="none" placeholder="请输入邮箱" clearable></u--input>
			</u-form-item>

			<u-form-item label="电话" prop="phone" borderBottom required>
				<u--input type="text" v-model="userForm.phone" border="none" placeholder="请输入电话" clearable></u--input>
			</u-form-item>

			<u-form-item label="性别" prop="gender" borderBottom>
				<u-radio-group v-model="userForm.gender" placement="row">
					<u-radio :name="1">男</u-radio>
					<u-radio :name="0" style="margin-left: 10px;">女</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="昵称" borderBottom><u--input type="text" placeholder="请输入昵称" v-model="userForm.nick_name" border="none"></u--input></u-form-item>
			<u-form-item label="头像"><u-upload name="avatar" :fileList="avatarList" :maxCount="1" @afterRead="afterRead" @delete="deletePic" /></u-form-item>
		</u--form>
		<u-button type="primary" text="提交" @click="onSubmit"></u-button>
		<u-button type="error" text="重置" customStyle="margin-top: 10px" @click="onReset"></u-button>

		<u-gap height="20"></u-gap>
		<div>注册成功后的用户可用于登录</div>
	</view>
</template>

<script>
//导入用户接口
import * as UserAPI from '@/api/user.js';
import { getStorageUser,setStorageUser } from '@/utils/storage.js'; //本地存储数据

export default {
	data() {
		return {
			userForm: {
				//表单中的字段名与数据库中用户表的字段名要求一致
				id: null,
				name: '',
				email: '',
				phone: '',
				gender: 1,
				avatar: '',
				nick_name: ''
			},

			//规则:字母数字

			//上传图片后回显
			avatarList: [],

			rules: {
				name: {
					type: 'string',
					required: true,
					pattern: /^[a-z0-9]{3,12}$/i,
					message: '3-12字符',
					trigger: ['blur', 'change']
				},				
				email: {
					type: 'email',
					required: true,
					message: '无效的邮箱地址',
					trigger: ['blur', 'change']
				},
				phone: {
					type: 'string',
					required: true,
					pattern: /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/,
					message: '无效的手机号码',
					trigger: ['blur', 'change']
				}
			}
		};
	},
	onReady() {
		// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
		this.$refs.form1.setRules(this.rules);
	},

	//生命周期钩子函数，实例被创建好了后被调用 this.
	created() {
		let id = getStorageUser().id;
		UserAPI.getDetailById(id).then(result => {
			this.userForm = result.data; //看接口文档，知道data是对应的用户对象

			//在上传图片组件中显示图片头像
			this.avatarList = [];
			this.avatarList.push({
				url: this.$fullUrl(this.userForm.avatar)
			});
		});
	},
	methods: {
		// 删除图片
		deletePic(event) {
			console.log(event);
			this.avatarList = []; //已上传的文件如何删除？
		},
		// 新增图片
		afterRead({ file }) {
			console.log(file);

			UserAPI.uploadAvatar(file).then(result => {
				console.log(result);
				//重新生成显示的图片url
				this.avatarList = [];
				this.avatarList.push({
					url: this.$fullUrl(result.url)
				});
				//设置用户表中的字段值
				this.userForm.avatar = result.url;
			});
		},

		//处理提交保存
		onSubmit() {			
			// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
			this.$refs.form1
				.validate()
				.then(valid => {
					if (valid) {
						//注意传递过去的参数user的属性名
						let user = this.userForm;						
						UserAPI.update(user).then(result => {
							let {id,name} = user;
							//保存用户信息（id,name） 注意：还是处于未登录
							setStorageUser({id,name});
							uni.showToast({
								title: "更新成功！",
								icon : "success"
							});
							setTimeout(()=>{
								uni.navigateBack({
									delta:1,   //	url: '/pages/user/User'			
								});								
							},1000)							
						});
					}
				})
				.catch(() => {
					uni.$u.toast('校验失败');
				});
		},

		onReset() {
			this.$refs.form1.resetFields();
			setTimeout(() => {
				this.$refs.form1.clearValidate();
			}, 10);
		}
	}
};
</script>
<style lang="scss" scoped></style>
